package au.edu.utas.yu_qiao_group.luckyman.ui.recordlist;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Environment;
import android.view.View;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ShareManager {
  public static Bitmap getBitmapByView(View headerView) {
    int h = headerView.getHeight();
    Bitmap bitmap = Bitmap.createBitmap(headerView.getWidth(), h, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    headerView.draw(canvas);
    return bitmap;
  }

  public static Bitmap compressImage(Bitmap image) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 10, baos);
    int options = 100;
    while (baos.toByteArray().length / 1024 > 400) {
      baos.reset();
      image.compress(Bitmap.CompressFormat.JPEG, options, baos);
      options -= 10;
    }
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
    return bitmap;
  }

  public static File bitMap2File(File path, Bitmap bitmap) {
    File f = new File(path, "share" + ".jpg");
    if (f.exists()) {
      f.delete();
    }
    try {
      FileOutputStream out = new FileOutputStream(f);
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
      out.flush();
      out.close();
      bitmap.recycle();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      return f;
    }
  }

}
